<?php
	require '../biz/backend.php';

	class action extends backend
	{
		var $get_privilege_id = '86';
		var $post_privilege_id = '86';

		function do_post()
		{
			$return = array( 'status'=>0,'msg'=>'可以创建或修改栏目' );

			$ename = trim(isset($_POST['ename'])?$_POST['ename']:"");
			$pid = trim(isset($_POST['pid'])?$_POST['pid']:"");
			$id = trim(isset($_POST['id'])?$_POST['id']:"");

			if ( $pid =='' ||  ! preg_match( '!^\d+$!', $pid ) )
			{
				echo json_encode ( array( 'status'=>1, 'msg'=>'父栏目信息不正确' ) );
				exit;
			}

			if( ! preg_match( '!^\w+$!', $ename ) )
			{
				echo json_encode ( array( 'status'=>1, 'msg'=>'栏目的英文名称只能是英文字母' ) );
				exit;
			}

			//修改栏目时检查
			if ( $id !='' && ! preg_match( '!^\d+$!', $id ) )
			{
				echo json_encode ( array( 'status'=>1, 'msg'=>'栏目信息不正确' ) );
				exit;
			}

			$database = load( 'database' );

			$sql = "select id from cate where ename='" . $ename . "' and parent_id=" . $pid;
			$data = $database->select( $sql );

			//添加栏目判断栏目是否存在
			if ( isset( $data[0] ) && $id=='' )
			{
				echo json_encode ( array( 'status'=>1, 'msg'=>'该栏目已存在' ) );
				exit;
			}

			if ( $id !='' )
			{
				//修改栏目父栏目不能是自身
				if ( $id == $pid )
				{
					echo json_encode ( array( 'status'=>1, 'msg'=>'父栏目不能是自身' ) );
					exit;
				}


				$cate = load( 'biz.cate' );

				//判断是否是移动到自己的子栏目下
				$ischild = $cate->isChild( $id, $pid );
				if ( $ischild )
				{
					echo json_encode ( array( 'status'=>1, 'msg'=>'父栏目不能是自身的子栏目' ) );
					exit;
				}

				//修改栏目判断栏目是否存在
				$cateinfo = $cate->get( array( 'id'=>$id ) );
				if ( ( $cateinfo['ename'] != $ename || $cateinfo['parent_id'] != $pid ) && isset( $data[0] ) )
				{
					echo json_encode ( array( 'status'=>1, 'msg'=>'该栏目已存在' ) );
					exit;
				}
			}

			echo json_encode ( $return );

		}
	}

	$action = new action();
	$action->run();
?>